import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

// 插件。可以监听 所有的mutation提交
const myPlugin = (store) => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    console.log('mutation', mutation)
    // 数据持久化操作
    localStorage.setItem('state', JSON.stringify(state))
  })
}
export default new Vuex.Store({
  state: {
    token: JSON.parse(localStorage.getItem('state'))?.token || '',
    list: [],
    total: 0,
  },
  plugins: [myPlugin],
  getters: {},
  mutations: {
    set_token(state, token) {
      state.token = token
    },
    set_list(state, { list, total }) {
      state.list = [...state.list, ...list]
      state.total = total
    },
  },
  actions: {
    async fetchList({ commit }, data) {
      const res = await axios.get('/api/list', { params: data })
      // console.log(res.data.data)
      const list = res.data.data.list
      const total = res.data.data.total
      commit('set_list', { list, total })
      return { code: 0, msg: 'success' }
    },
  },
  modules: {},
})
